package com.ruoyi.business.controller;

import java.io.IOException;
import java.io.InputStream;
import java.util.Collections;
import java.util.List;

import com.ruoyi.business.service.IProcessService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.file.FileUploadUtils;
import org.activiti.engine.repository.ProcessDefinition;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.business.domain.DefinitionDetail;
import com.ruoyi.business.service.IDefinitionDetailService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;

/**
 * 流程定义明细Controller
 * 
 * @author wolfcode
 * @date 2021-08-26
 */
@Controller
@RequestMapping("/business/definitionDetail")
public class DefinitionDetailController extends BaseController
{
    private String prefix = "business/definitionDetail";

    @Autowired
    private IDefinitionDetailService definitionDetailService;

    @Autowired
    private IProcessService processService;


    @RequiresPermissions("business:definitionDetail:view")
    @GetMapping()
    public String definitionDetail(Long definitionId, /*Model model,*/ModelMap mmap)
    {

        //Model 与 ModelMap 是一致
       /* model.addAttribute("definitionId", definitionId);*/
        mmap.put("definitionId", definitionId);

        return prefix + "/definitionDetail";
    }

    /**
     * 查询流程定义明细列表
     */
    @RequiresPermissions("business:definitionDetail:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(DefinitionDetail definitionDetail)
    {
        startPage();
        List<DefinitionDetail> list = definitionDetailService.selectDefinitionDetailList(definitionDetail);
        return getDataTable(list);
    }

    /**
     * 导出流程定义明细列表
     */
    @RequiresPermissions("business:definitionDetail:export")
    @Log(title = "流程定义明细", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(DefinitionDetail definitionDetail)
    {
        List<DefinitionDetail> list = definitionDetailService.selectDefinitionDetailList(definitionDetail);
        ExcelUtil<DefinitionDetail> util = new ExcelUtil<DefinitionDetail>(DefinitionDetail.class);
        return util.exportExcel(list, "流程定义明细数据");
    }

    /**
     * 新增流程定义明细
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存流程定义明细
     */
    @RequiresPermissions("business:definitionDetail:add")
    @Log(title = "流程定义明细", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(DefinitionDetail definitionDetail)
    {
        return toAjax(definitionDetailService.insertDefinitionDetail(definitionDetail));
    }

    /**
     * 修改流程定义明细
     */
    @GetMapping("/edit/{definitionInfoId}")
    public String edit(@PathVariable("definitionInfoId") Long definitionInfoId, ModelMap mmap)
    {
        DefinitionDetail definitionDetail = definitionDetailService.selectDefinitionDetailById(definitionInfoId);
        mmap.put("definitionDetail", definitionDetail);
        return prefix + "/edit";
    }

    /**
     * 修改保存流程定义明细
     */
    @RequiresPermissions("business:definitionDetail:edit")
    @Log(title = "流程定义明细", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(DefinitionDetail definitionDetail)
    {
        return toAjax(definitionDetailService.updateDefinitionDetail(definitionDetail));
    }

    /**
     * 删除流程定义明细
     */
    @RequiresPermissions("business:definitionDetail:remove")
    @Log(title = "流程定义明细", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(definitionDetailService.deleteDefinitionDetailByIds(ids));
    }

    @RequiresPermissions("business:definitionDetail:upload")
    @RequestMapping( "/upload")
    @ResponseBody
    public AjaxResult upload(Long definitionId, MultipartFile file) throws IOException {

        if(file != null && file.getSize() > 0){
            //xxx.jpg -->jpg     xxx.zip --- zip
            String ext = FilenameUtils.getExtension(file.getOriginalFilename());
            if("bpmn".equalsIgnoreCase(ext) || "zip".equalsIgnoreCase(ext)){
                //保存流程图文件
                String filePath = FileUploadUtils.upload(file);
                //  /profile//2021/08/26/ea11835a-1167-42ce-9e7a-9afabe41a45a.bpmn
                filePath = RuoYiConfig.getProfile() + filePath.substring(Constants.RESOURCE_PREFIX.length()+1);
                //D:/ruoyi/uploadPath/2021/08/26/ea11835a-1167-42ce-9e7a-9afabe41a45a.bpmn
                //1：流程部署
                //2：维护t_definition_detail(添加一条记录)
                definitionDetailService.saveProcessDefinition(definitionId, filePath);
                System.out.println(filePath);
                return AjaxResult.success("部署成功");
            }else{
                return AjaxResult.error("上传的文件必须是zip数据格式或者bpmn数据格式");
            }
        }else{
            return AjaxResult.error("上传的文件不能为空文件");
        }
    }


    @RequiresPermissions("business:definitionDetail:readResource")
    @Log(title = "流程定义明细", businessType = BusinessType.DELETE)
    @RequestMapping( "/readResource")
    public void remove(String deploymentId, String type, HttpServletResponse response) throws IOException {

        InputStream inputStream = null;  //将流程数据转换流， 输出要页面

        ProcessDefinition definition = processService.selectProcessDefinitionByDeploymentId(deploymentId);

        if("xml".equalsIgnoreCase(type)){
            inputStream = processService.getResourceAsStream
                    (definition.getDeploymentId(), definition.getResourceName());
        }else if("png".equalsIgnoreCase(type)){
            inputStream = processService.getProcessImage(definition.getId(),
                    Collections.EMPTY_LIST,Collections.EMPTY_LIST);
        }

        IOUtils.copy(inputStream,  response.getOutputStream());
    }

}
